import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Dropdown, Modal, Form, Input } from 'antd';
import { INIT_STATE, SAVE_LOGIN_INFO } from '@/reducers/common';
import { push } from 'redux-first-history';
import styles from './index.less'
import {
    DownOutlined,
    QuestionCircleOutlined
} from '@ant-design/icons';
import { logout, switchAccount, updatePwd } from '@/apis/user/index'
import DefaultModal from '@/components/DefaultModal';
import { getFirstPermission } from '@/utils/util';
import menuData from '../SiderMenu/menuData';

//用户退出系统，修改密码设置 切换账号
const SystemSetting = () => {
    let loginInfo = useSelector((state: { common: initStateType }) => state.common.loginInfo)
    let tenantInfo = useSelector((state: { common: initStateType }) => state.common.tenantInfo)
    const [visible, setVisible] = useState(false);
    const [submitting, setSubmitting] = useState(false);
    const [LoginVisible, setLoginVisible] = useState(false)
    loginInfo = typeof loginInfo === 'boolean' ? {} : loginInfo
    tenantInfo = typeof tenantInfo === 'boolean' ? {} : tenantInfo
    const [form] = Form.useForm();
    const dispatch = useDispatch()
    function showModalHandle() {
        form.resetFields();
        setVisible(true);
    }
    //切换账号
    function showLoginModalHandle() {
        setLoginVisible(true)
    }
    function logoutHandle() {
        Modal.confirm({
            title: '您确定要退出？',
            icon: <QuestionCircleOutlined />,
            async onOk() {
                await logout({})
                dispatch({ type: INIT_STATE });
                push('/login')
                localStorage.clear()
            }
        })
    }

    useEffect(() => {
        setVisible(visible);
    }, [visible]);

    useEffect(() => {
        setSubmitting(submitting);
    }, [submitting])

    const menu = [
        {
            label: <span style={{ padding: '0 32px 0 8px' }} >修改密码</span>,
            onClick: showModalHandle,
            key: "1"
        },
        {
            label: <span style={{ padding: '0 32px 0 8px' }} >退出系统</span>,
            onClick: logoutHandle,
            key: "2"
        }
    ]
    if (loginInfo.multiAccountList && loginInfo.multiAccountList.length > 1) {
        menu.unshift({
            label: <span style={{ padding: '0 32px 0 8px' }} >切换账号</span>,
            onClick: showLoginModalHandle,
            key: "3"
        })
    }
    function cancelHandle() {
        setVisible(false)
    }
    function okHandle() {
        form.validateFields().then(async (values) => {
            setSubmitting(true);
            try {
                await updatePwd(values)
                form.resetFields()
                localStorage.clear()
                dispatch({ type: INIT_STATE });
                push('/login')
            } finally {
                setSubmitting(false);
            }
        })
    }

    function validateToNextPassword(_rule: any, value: any) {

        const newPasswordAgain = form.getFieldValue('newPasswordAgain');
        const newPassword = value;
        const oldPassword = form.getFieldValue('oldPassword');

        if (newPasswordAgain && newPassword) {
            console.log('两次密码不一致')
            if (newPasswordAgain != newPassword) {
                console.log('两次密码不一致')
                return Promise.reject('两次密码不一致')
            }
        }

        if (oldPassword && newPassword) {
            if (oldPassword === newPassword) {
                return Promise.reject('新密码不能跟原密码一样')
            }
        }

        return Promise.resolve();
    }

    function validateToPasswordAgain(_rule: any, value: any) {

        const newPasswordAgain = value;
        const newPassword = form.getFieldValue('password');

        if (newPasswordAgain && newPassword) {
            console.log('两次密码不一致')
            if (newPasswordAgain != newPassword) {
                console.log('两次密码不一致')
                return Promise.reject('两次密码不一致')
            }
        }

        return Promise.resolve();
    }
    const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
    };
    let multiAccountList = loginInfo.multiAccountList || []
    //选择账号切换
    async function onLoginOk(values: UserSwitchAccountParam) {
        let res = await switchAccount(values)
        dispatch({
            type: SAVE_LOGIN_INFO,
            data: res.data
        })
        setLoginVisible(false)
        let url = await getFirstPermission(menuData)
        window.location.href = '/#' + url;
    }
    return (
        <>
            <Dropdown menu={{ items: menu }} >
                <span style={{ "cursor": "pointer", display: 'flex', alignItems: "center" }}>
                    {
                        tenantInfo.userName ?
                            <span className={styles.tenantName} >{tenantInfo.userName}</span> : null
                    }
                    {loginInfo.userName}  <DownOutlined /></span>
            </Dropdown >

            <Modal
                title="修改密码"
                open={visible}
                confirmLoading={submitting}
                onCancel={cancelHandle}
                onOk={okHandle}
            >
                <Form form={form} {...layout}>
                    <Form.Item
                        label="原 密 码"
                        name="oldPassword"
                        rules={[
                            { required: true, message: '请输入原密码' },
                            { max: 20, message: '最多20个字符' },
                            { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\w]{8,}$/, message: '密码至少8个字符，且必须包含字母和数字' }
                        ]}
                    >
                        <Input placeholder="请输入原密码" />
                    </Form.Item>

                    <Form.Item
                        label="新 密 码"
                        name="password"
                        rules={[
                            { required: true, message: '请输入新密码' },
                            { max: 20, message: '最多20个字符' },
                            { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\w]{8,}$/, message: '密码至少8个字符，且必须包含字母和数字' },
                            { validator: validateToNextPassword }
                        ]}
                    >
                        <Input placeholder="请输入新密码" />
                    </Form.Item>

                    <Form.Item
                        label="确认密码"
                        name="confirmPassword"
                        rules={[
                            { required: true, message: '请再次确认密码' },
                            { validator: validateToPasswordAgain }
                        ]}
                    >
                        <Input placeholder="请确认密码" />
                    </Form.Item>
                </Form>
            </Modal>
            <DefaultModal
                onCancel={() => setLoginVisible(false)}
                onOk={onLoginOk}
                open={LoginVisible}
                title='选择您的账号'
                list={[
                    {
                        name: "loginName",
                        label: "选择账号",
                        type: "select",
                        options: multiAccountList.map(item => ({ label: item || '', value: item }))
                    }
                ]}
            ></DefaultModal>

        </>
    )
}

export default SystemSetting